const { ethers } = require("hardhat");
const fs = require('fs');

async function main() {
  console.log("开始测试合约功能...");

  // 读取部署的合约地址
  const addresses = JSON.parse(fs.readFileSync('deployed-addresses.json', 'utf8'));
  
  // 获取签名者
  const [owner, buyer] = await ethers.getSigners();
  console.log("合约所有者:", owner.address);
  console.log("买家地址:", buyer.address);

  // 连接到已部署的合约
  const book1155 = await ethers.getContractAt("BOOK1155", addresses.BOOK1155);
  const marketplace = await ethers.getContractAt("TokenMarketplace", addresses.TokenMarketplace);
  const traceBook = await ethers.getContractAt("TraceBook", addresses.TraceBook);
  const ipfsManager = await ethers.getContractAt("BookIPFSManager", addresses.BookIPFSManager);

  // 测试数据
  const testBook = {
    id: 1,
    ISBN: "978-0123456789",
    amount: 10,
    imageURI: "https://example.com/book-cover.jpg",
    price: ethers.utils.parseEther("0.1"), // 0.1 ETH
    contentHash: "QmTestContentHash123456789",
    metadataHash: "QmTestMetadataHash123456789",
    previewHash: "QmTestPreviewHash123456789",
    isEncrypted: false,
    encryptionKey: ""
  };

  try {
    // 1. 铸造图书代币
    console.log("\n=== 步骤1: 铸造图书代币 ===");
    const mintTx = await book1155.mint(
      testBook.id,
      testBook.ISBN,
      testBook.amount,
      testBook.imageURI,
      testBook.price,
      testBook.contentHash,
      testBook.metadataHash,
      testBook.previewHash,
      testBook.isEncrypted,
      testBook.encryptionKey
    );
    await mintTx.wait();
    console.log("✅ 图书代币铸造成功");

    // 检查铸造结果
    const balance = await book1155.balanceOf(owner.address, testBook.id);
    console.log(`📚 所有者拥有的代币数量: ${balance.toString()}`);

    // 2. 查看IPFS内容
    console.log("\n=== 步骤2: 查看IPFS内容 ===");
    const ipfsContent = await ipfsManager.getBookIPFSContent(testBook.ISBN);
    console.log("📖 IPFS内容信息:");
    console.log("  内容哈希:", ipfsContent[0]);
    console.log("  元数据哈希:", ipfsContent[1]);
    console.log("  预览哈希:", ipfsContent[2]);
    console.log("  上传时间:", new Date(Number(ipfsContent[3]) * 1000).toLocaleString());
    console.log("  是否加密:", ipfsContent[4]);

    // 3. 设置市场授权
    console.log("\n=== 步骤3: 设置市场授权 ===");
    const approvalTx = await book1155.setApprovalForAll(addresses.TokenMarketplace, true);
    await approvalTx.wait();
    console.log("✅ 市场授权设置成功");

    // 4. 创建销售列表
    console.log("\n=== 步骤4: 创建销售列表 ===");
    const listingTx = await marketplace.createListing(
      addresses.BOOK1155,
      testBook.id,
      5 // 上架5本
    );
    const receipt = await listingTx.wait();
    console.log("✅ 销售列表创建成功");

    // 查看上架信息
    const activeListings = await marketplace.getAllActiveListings();
    console.log("📋 当前上架的图书:");
    for (let i = 0; i < activeListings.length; i++) {
      const listing = activeListings[i];
      console.log(`  ID: ${listing.listingId}`);
      console.log(`  ISBN: ${listing.ISBN}`);
      console.log(`  数量: ${listing.amount}`);
             console.log(`  价格: ${ethers.utils.formatEther(listing.price)} ETH`);
    }

    // 5. 买家购买图书
    console.log("\n=== 步骤5: 买家购买图书 ===");
    const purchaseAmount = 2;
    const totalPrice = testBook.price * BigInt(purchaseAmount);
    
    const purchaseTx = await marketplace.connect(buyer).executePurchase(
      0, // listingId
      purchaseAmount,
      { value: totalPrice }
    );
    await purchaseTx.wait();
    console.log("✅ 购买成功");

    // 检查买家余额
    const buyerBalance = await book1155.balanceOf(buyer.address, testBook.id);
    console.log(`💰 买家拥有的代币数量: ${buyerBalance.toString()}`);

    // 6. 查看买家拥有的图书信息
    console.log("\n=== 步骤6: 查看买家拥有的图书 ===");
    const ownedBooks = await marketplace.getOwnInformation(buyer.address);
    console.log("📚 买家拥有的图书代码:");
    ownedBooks.forEach((tokenCode, index) => {
      console.log(`  ${index + 1}. ${tokenCode}`);
    });

    // 7. 查看追溯信息
    console.log("\n=== 步骤7: 查看追溯信息 ===");
    if (ownedBooks.length > 0) {
      const traceInfo = await traceBook.traceBook(ownedBooks[0]);
      console.log("🔍 第一本书的追溯信息:");
      console.log(traceInfo);
    }

    console.log("\n🎉 所有测试完成！");

  } catch (error) {
    console.error("❌ 测试过程中出现错误:", error.message);
  }
}

main()
  .then(() => process.exit(0))
  .catch((error) => {
    console.error(error);
    process.exit(1);
  }); 